#!/usr/bin/env python3

def menu(title='菜单标题', quitStr='退出'):
    """
    创建菜单对象
    """
    obj = {}
    obj['title'] = title
    obj['quitStr'] = quitStr
    obj['level'] = 0
    obj['items'] = []

    return obj

def add(msg, handle=None, menuObj=None):
    """
    给菜单添加项
    """
    menuObj = menu() if menuObj == None else menuObj

    item = {}
    item['msg'] = msg
    if type(handle) == dict:
        handle['level'] = menuObj['level'] + 1
    item['handle'] = handle
    menuObj['items'].append(item)

    return menuObj

def showItems(items, level):
    for index, it in enumerate(items):
        print("%s%d. %s" % ('    ' * level, index + 1, it['msg']))

def getInput(num, level):
    while True:
        s = input("%s请输入[1 - %d]: " % ('    ' * level, num))
        if not s:
            continue
        n = int(s)
        if 1 <= n <= num:
            return n

def run(menuObj):
    """
    运行菜单程序
    """

    #  添加退出菜单项
    addFlags = True
    for x in menuObj['items']:
        if None in x.values():
            addFlags = False
            break

    if addFlags:
        if menuObj['level'] == 0:
            add(menuObj['quitStr'], None, menuObj)
        else:
            add('返回上一级', None, menuObj)

    itemNum = len(menuObj['items'])

    #  循环菜单执行
    while True:
        #  打印菜单标题
        print("%s%s" % ('    ' * menuObj['level'], menuObj['title']))
        #  输出菜单项
        showItems(menuObj['items'], menuObj['level'])

        #  获取用户输入
        i = getInput(itemNum, menuObj['level'])

        #  根据用户输入执行菜单项
        handle = menuObj['items'][i - 1]['handle']
        if not handle:
            break
        elif type(handle) == dict:
            run(handle)
        else:
            handle(i)

def t(index):
    if index == 1:
        print("三角形主处理函数")
    elif index == 2:
        print("右上三角形处理函数")
    elif index == 3:
        print("左上三角形处理函数")
    elif index == 4:
        print("右下三角形处理函数")

def g(index):
    if index == 2:
        print("正方形处理函数")
    elif index == 3:
        print("棱形处理函数")

if __name__ == "__main__":
    m = menu()
    submenu = menu('三角形子菜单')
    sub2menu = menu('三角形三角形子菜单')

    add("三角形", submenu, m)
    add("正方形", g, m)
    add("棱形", g, m)

    add("三角形1", t, submenu)
    add("三角形2", t, submenu)
    add("三角形3", t, submenu)
    add("三角形4", t, submenu)
    add('三角形子菜单子菜单', sub2menu, submenu)

    add("三角形A", t, sub2menu)
    add("三角形B", t, sub2menu)
    add("三角形C", t, sub2menu)
    add("三角形D", t, sub2menu)

    run(m)

